import 'package:enterprise_v6_app/app/core/http/http.dart';
import 'package:enterprise_v6_app/app/core/utils/interface.dart';
import 'package:enterprise_v6_app/app/data/api/special_list.dart';
import 'package:enterprise_v6_app/app/data/entities/application/execute_entity.dart';
import 'package:enterprise_v6_app/app/modules/application/special_operation/special_list/job_ticket/common/common_work_all/common_work_all_controller.dart';
import 'package:get/get.dart';

class CommonSafetyDisclosureController extends GetxController {
  //作业总页面controller
  final workAllPageController = Get.find<CommonWorkAllController>();

  //作业票id
  late String ticketReceiptId;

  //气体检测计时
  int milliseconds = 0;

  //安全交底
  List<ExecuteTicketDiscloseList> ticketDiscloseList = [];

  @override
  void onInit() {
    super.onInit();
    // 初始化页面列表
    initData();
    // 获取数据气体检测有效期
    if (workAllPageController.receiptType == 1) {
      getTicketReceiptValidDate();
    }
  }

  ///初始化数据
  initData() async {
    //作业票id
    ticketReceiptId = workAllPageController.executeEntity.ticketReceiptId!;
    //获取数据-安全措施数据
    final res = await HttpUtil().generateGetRequest<List<ExecuteTicketDiscloseList>>(
        Interface.getListDiscloseById,
        queryParameters: {'ticketReceiptId': workAllPageController.executeEntity.ticketReceiptId}).execute();
    res.onSuccess((result) {
      workAllPageController.executeEntity.ticketDiscloseList = result.data;
    });
    //赋值
    ticketDiscloseList = workAllPageController.executeEntity.ticketDiscloseList!;
    addInitData(workAllPageController.businessType);
    update();
  }

  ///如果查询到时数据为空,则添加初始数据
  ///[businessType]1：动火作业 2：受限空间作业 3：盲板抽堵作业 4：高处作业 5：吊装作业 6：临时用电作业 7：动土作业 8：断路作业
  void addInitData(String businessType) {
    if (ticketDiscloseList.isEmpty) {
      ticketDiscloseList.add(ExecuteTicketDiscloseList()
        ..discloseType = 0
        ..ticketReceiptId = ticketReceiptId);
      ticketDiscloseList.add(ExecuteTicketDiscloseList()
        ..discloseType = 1
        ..ticketReceiptId = ticketReceiptId);
      // 只有动火作业在安全交底处有监护人
      if (businessType == '1') {
        ticketDiscloseList.add(ExecuteTicketDiscloseList()
          ..discloseType = 2
          ..ticketReceiptId = ticketReceiptId);
      }
    }
  }

  ///获取数据气体检测有效期
  getTicketReceiptValidDate() async {
    //如果要显示才去请求
    final res = await SpecialListApis.getListConfigByTicketReceiptId(ticketReceiptId).execute();
    res.onSuccess((result) {
      if (result.data != null && result.data!.gasDetectionValidDate != 0) {
        milliseconds = result.data!.gasDetectionValidDate!;
        update();
      }
    });
  }
}
